package org.dtrd.modules.content.articles.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.CharUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.dtrd.modules.content.articles.entity.bean.GroupItem;
import org.dtrd.modules.content.articles.entity.bean.Vocabulary;
import org.dtrd.modules.content.articles.entity.po.DtrdExtEmsYwWords;
import org.dtrd.modules.content.articles.mapper.DtrdExtEmsYwWordsMapper;
import org.dtrd.modules.content.articles.service.IDtrdExtEmsYwWordsService;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author 萧
 * @date 2021-08-25 17:37:47
 **/
@Service
@DS("multi-datasource1")
public class DtrdExtEmsYwWordsServiceImpl extends ServiceImpl<DtrdExtEmsYwWordsMapper, DtrdExtEmsYwWords> implements IDtrdExtEmsYwWordsService {

    @Override
    public List<Vocabulary> getWordList(String keyWord) {
        List<Vocabulary> list = baseMapper.getWordList(keyWord);
        if (CollectionUtil.isNotEmpty(list)) {
            list.forEach(vo -> {
//                vo.setWordNamePinYin(PinyinUtil.getPinyin(vo.getWordName()));
                vo.setFirstLetter(Character.toUpperCase(PinyinUtil.getFirstLetter(vo.getWordName().charAt(0))));
            });
        }
        return list;
    }

    @Override
    public List<GroupItem<Character, Vocabulary>> getGroupWordList(String keyWord) {
        List<Vocabulary> list = getWordList(keyWord);
        if (CollectionUtil.isNotEmpty(list)) {
            List<GroupItem<Character, Vocabulary>> dataList = new ArrayList<>(list.size() / 2);
            Map<Character, List<Vocabulary>> map = new TreeMap<>();
            list.stream().peek(vo -> {
                if (!CharUtil.isLetter(vo.getFirstLetter())) {
                    // 非字母同意转换为 #
                    vo.setFirstLetter((char) ('Z' + 1));
                }
            }).forEach(vo -> {
                List<Vocabulary> tmpList = map.getOrDefault(vo.getFirstLetter(), new ArrayList<>());
                tmpList.add(vo);
                map.put(vo.getFirstLetter(), tmpList);
            });
            map.keySet().stream().map(key -> new GroupItem<>(key, map.get(key)))
                    .forEach(dataList::add);
            return dataList;
        }
        return null;
    }


}
